home *** CD-ROM | disk | FTP | other *** search
- Path: crl.crl.com!not-for-mail
- From: bobfry@crl.com (Robert Fry)
- Newsgroups: comp.lang.c
- Subject: Re: char* still alive after free ???
- Date: 15 Apr 1996 13:58:43 -0700
- Organization: CRL Dialup Internet Access
- Message-ID: <4kuda3$5vc@crl.crl.com>
- References: <317269EA.11BB93C2@studbox.uni-stuttgart.de>
- NNTP-Posting-Host: crl.com
-
- Markus Heller <Markus.Heller@studbox.uni-stuttgart.de> writes:
-
- >I have a global variable :
-
- >char *text=NULL;
-
- >I want to use it to store different "strings" (at diffreent times).
- >E.g., if I want to sore 10 characters in text, I do a
- >text=(char *) malloc(10*sizeof(char));
- >When I want to use text to store 3 other characters, I first do a
- >free(text); text=NULL; and finally a
- >text=(char *) malloc(3*sizeof(char));
- >But to my surprise there are still the 4thh to 10th charcter of
- >text contained before the free(text)/malloc... ???
- >This happens under linux, but why ?
-
- I think that a better question would be "why not?" There's nothing in C
- to prevent malloc from returning a pointer to just-freed space if the
- data fits.
-
- Since I suspect you're interested in finding a way to determine where the
- newly-stored string ends, perhaps you might want to look at putting in
- some sort of termination character at the end of your string? Such as '\0'?
- Either that, or store the number of significant characters in your 'new'
- string. You should not rely on the character at the end of a malloced
- string having any specified value --- and never rely on anything about
- space that is not currently malloced.
-
- Bob
-